package cn.my.springHDFS.service;


import cn.my.springHDFS.domain.AdminUser;
import cn.my.springHDFS.repository.AdminRepository;
import cn.my.springHDFS.util.WebHDFSProcessor;
import com.mongodb.WriteResult;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import us.codecraft.webmagic.Spider;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Leo on 2017/4/12.
 * 管理员实现类
 */
@Repository
public class ManagementServiceImpl {

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserHistoryServiceImpl userHistoryService;

//    /**
//     * 查询所有Admin的信息
//     * @return
//     */
//    public Page<AdminUser> findAllAdminUser(String administrator, Integer current, Integer size){
//        Pageable pageable = PageableTools.addLibraryDateSortForDesc(current, size);
//        return adminRepository.findByAdministratorLike(administrator, pageable);
//    }

    /**
     * 通过账号和密码查找管理员
     * @param adminAccount
     * @param adminPassword
     * @return
     */
    public AdminUser findByAdminAccountAndAdminPassword(String adminAccount, String adminPassword) {
        return adminRepository.findByAdminAccountAndAdminPassword(adminAccount, adminPassword);
    }

    /**
     * 通过账号查找管理员
     * @param adminAccount
     * @return
     */
    public AdminUser findByAdminAccount(String adminAccount){
        return adminRepository.findByAdminAccount(adminAccount);
    }

    /**
     * 获取WebHDFS的状态
     * @return
     */
    public Spider getWebHDFS_Status(Spider spider, String ipaddress){
        spider.addUrl("http://" + ipaddress + ":50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeStatus");
        spider.run();
        return spider;
    }

    /**
     * 管理员登录状态
     * @param adminUser
     * @return
     */
    public boolean adminLoginInfo(AdminUser adminUser, boolean LogoutOrIn, HttpServletRequest httpServletRequest){
        Query query = Query.query(Criteria.where("adminAccount").is(adminUser.getAdminAccount()));
        Update update = new Update();
        try{
            if (LogoutOrIn){
                update.set("adminLoginTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).set("adminLoginStatus", LogoutOrIn);
                boolean isUpsertLogin = mongoTemplate.upsert(query, update, AdminUser.class).wasAcknowledged();
                boolean loginLogger = userHistoryService.addUserLoginLogger(adminUser, httpServletRequest);
                return !isUpsertLogin && loginLogger;
            }
            else {
                update.set("adminLogoutTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).set("adminLoginStatus", LogoutOrIn);
                boolean isUpsertLogout = mongoTemplate.upsert(query, update, AdminUser.class).wasAcknowledged();
                boolean logoutLogger = userHistoryService.addUserLogoutLogger(adminUser, httpServletRequest);
                return !isUpsertLogout && logoutLogger;
            }
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

//    /**
//     * 添加普通管理员(Only secondAdmin)
//     * @return
//     */
//    public boolean addSecondAdmin(AdminUser adminUser){
//        //获取超级管理员添加的账号名称，如果数据库存在则返回false
//        String adminAccount = adminUser.getAdminAccount();
//        List<AdminUser> adminUsers = mongoTemplate.find(new Query(Criteria.where("adminAccount").is(adminAccount)), AdminUser.class);
//        if (adminUsers.size() != 0){
//            return false;
//        }else{
//            adminUser.setAddAdminDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//            adminUser.setAdminLevel("ROLE_SECONDADMIN");
//            adminRepository.save(adminUser);
//            return true;
//        }
//    }

//    /**
//     * 删除普通管理员
//     * @param adminUser
//     * @return
//     */
//    public boolean deleteSecondAdmin(String adminUser){
//        WriteResult writeResult = mongoTemplate.remove(new Query(Criteria.where("adminAccount").is(adminUser)), AdminUser.class);
//        return writeResult.isUpdateOfExisting();
//    }

    /**
     * 修改管理员密码
     * @param adminUser
     * @param newPassword
     * @return
     */
    public boolean modifyAdminPassword(String adminUser, String newPassword){
        Criteria criteria = Criteria.where("adminAccount").is(adminUser);
        Update update = Update.update("adminPassword", newPassword);
        WriteResult writeResult = mongoTemplate.updateFirst(new Query(criteria), update, AdminUser.class);
        return writeResult.isUpdateOfExisting();
    }
}
